import useLocale from '@/utils/useLocale';
import React, { useEffect, useState } from 'react';
import moment from 'moment/moment';
import instance from '@/utils/request';
import { Card, Divider, Empty, Grid, Skeleton, Slider, Space, Statistic, Typography } from '@arco-design/web-react';
import { dayjs } from '@arco-design/web-react/es/_util/dayjs';
import { Chart, Interval, LineAdvance, Tooltip } from 'bizcharts';
import { ProduceRecordResponse } from '@/constants/type';

const { Row, Col } = Grid;

const ProducePanel = (props: {
  id: number
}) => {
  const t = useLocale();
  const [loading, setLoading] = useState<boolean>(false);
  const [origin, setOrigin] = useState<ProduceRecordResponse>();
  const [list, setList] = useState<{
    name: string,
    datetime: string,
    origin: number,
    increment: number,
  }[]>([]);
  const [acquisitionFrequency, setAcquisitionFrequency] = useState<{
    min: number,
    avg: number,
    max: number,
    dest: number
  }>({ min: 0, avg: 0, max: 0, dest: 0 });


  function refreshDeviceProduceData(data: ProduceRecordResponse, frequency: number) {
    data = data || origin;
    frequency = frequency || acquisitionFrequency.dest;
    const dataSeries = [];
    (data.parameterList || []).forEach((parameter, parameterIndex) => {
      let lastTime = null;
      let count1 = 0;
      let count2 = 0;
      (data.timeList || []).forEach((datetime, datetimeIndex) => {
        const originListElement = data.originList[datetimeIndex] || [];
        const incrementListElement = data.incrementList[datetimeIndex] || [];
        const now = dayjs(datetime, 'YYYY-MM-DD HH:mm:ss');
        if (lastTime == null) {
          lastTime = now;
        } else if (now.diff(lastTime, 'second') < frequency) {
          count1 = count1 + (originListElement[parameterIndex] || 0);
          count2 = count2 + (incrementListElement[parameterIndex] || 0);
        } else if (now.diff(lastTime, 'second') >= frequency || datetimeIndex === data.timeList.length - 1) {
          dataSeries.push({
            name: parameter.name,
            datetime: dayjs(datetime).format('HH:mm:ss'),
            origin: count1,
            increment: count2
          });
          lastTime = now;
          count1 = 0;
          count2 = 0;
        } else {
          count1 = count1 + (originListElement[parameterIndex] || 0);
          count2 = count2 + (incrementListElement[parameterIndex] || 0);
        }
      });
    });
    setList(dataSeries);
  }

  useEffect(() => {
    if (!!props.id) {
      const date = moment();
      setLoading(true);
      instance
        .post('/api/produce/record/origin', {
          deviceId: props.id,
          startDateTime: date.format('YYYY-MM-DD') + ' 00:00:00',
          endDateTime: date.format('YYYY-MM-DD') + ' 23:59:59'
        })
        .then((res) => {
          if (res.data.code === 200) {
            const data: ProduceRecordResponse = res.data.data;
            setOrigin(data);
            if ((data.timeList || []).length > 1) {
              const result = data.timeList.map(it => dayjs(it, 'YYYY-MM-DD HH:mm:ss').unix())
                .reduce((accumulator, num, index, array) => {
                  if (index < array.length - 1) {
                    // 计算差值并累加到总和
                    accumulator.sum += array[index + 1] - num;
                    // 递增差值数量
                    accumulator.count++;
                  }
                  return accumulator;
                }, { sum: 0, count: 0 }); // 初始累加器是一个对象，包含总和和数量
              // 设置平均采样率
              setAcquisitionFrequency({
                min: Math.min(60, parseFloat((result.sum / 100).toPrecision(2))),
                avg: parseFloat((result.sum / result.count).toPrecision(2)),
                max: Math.min(3600, parseFloat((result.sum / 2).toPrecision(2))),
                dest: result.sum / 100
              });
              // 设置默认采样率
              refreshDeviceProduceData(data, result.sum / 100);
            }
          }
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [props.id]);

  return (
    <Card>
      <Row>
        <Col span={24}>
          {!!loading ? (
            <Skeleton animation />
          ) : (
            (origin?.timeList || []).length === 0 ? (
              <Empty description={'请确保设备关联的物模型中至少存在一个参数包含产量能力'} />
            ) : (
              <>
                <Row align={'center'}>
                  <Col span={16}>
                    <Row align={'center'} justify={'start'}>
                      <Col span={24}>
                        <Space size={24}>
                          <Statistic extra={t['global.produce.acquisition.frequency.device']}
                                     value={acquisitionFrequency?.avg} groupSeparator precision={2} />
                          <Statistic extra={t['global.produce.acquisition.frequency.count']}
                                     value={origin?.timeList?.length}
                                     groupSeparator />
                        </Space>
                      </Col>
                    </Row>
                  </Col>
                  <Col span={8}>
                    <Space direction={'vertical'}>
                      <Statistic extra={t['global.produce.acquisition.frequency.dest']}
                                 value={acquisitionFrequency.dest}
                                 groupSeparator />
                      <Slider
                        disabled={loading}
                        min={acquisitionFrequency?.min} max={acquisitionFrequency?.max}
                        style={{ width: 280 }} defaultValue={acquisitionFrequency.dest}
                        formatTooltip={(val) => {
                          if (val / 3600 > 1) {
                            return (val / 3600).toFixed(2) + '小时';
                          } else if (val / 60 > 1) {
                            return (val / 60).toFixed(2) + '分钟';
                          } else {
                            return val + '秒';
                          }
                        }}
                        step={60}
                        onChange={(val) => setAcquisitionFrequency({
                          ...acquisitionFrequency,
                          dest: val as number
                        })}
                        onAfterChange={(val) => refreshDeviceProduceData(null, val as number)} />
                    </Space>
                  </Col>
                </Row>
                <Divider />
                <Typography.Title heading={6}>
                  {t['global.produce.origin.title']}
                </Typography.Title>
                <Row>
                  <Col span={24}>
                    {!!loading ? (
                      <Skeleton animation />
                    ) : (
                      <Chart padding={[20, 50, 70, 90]} autoFit height={350} data={list}>
                        <LineAdvance shape="smooth" area position="datetime*origin" color="name"> </LineAdvance>
                      </Chart>
                    )}
                  </Col>
                </Row>
                <Typography.Title heading={6}>
                  {t['global.produce.increment.title']}
                </Typography.Title>
                <Row>
                  <Col span={24}>
                    {!!loading ? (
                      <Skeleton animation />
                    ) : (
                      <Col span={24}>
                        <Chart padding={[20, 50, 60, 90]} autoFit height={350} data={list}>
                          <Interval position="datetime*increment" color="name"
                                    adjust={[{ type: 'dodge', marginRatio: 0 }]}>
                            <Tooltip shared />
                          </Interval>
                        </Chart>
                      </Col>
                    )}
                  </Col>
                </Row>
              </>
            )
          )}
        </Col>
      </Row>
    </Card>
  );
};

export default ProducePanel;